package com.kaisheng.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaisheng.entity.User;
import com.kaisheng.util.DBHelp;
import com.kaisheng.util.RowMapper;

public class UserDao {

	DBHelp<User> db = new DBHelp<User>();

	public User findByEmail(String email) {
		String sql = "SELECT id,`name`,`password`,pic,email FROM t_user WHERE email = ? ";
		return db.executeQueryForObject(sql, new UserRowMapper(), email);
	}
	public List<User> findByProjectId(String project_id) {
		String sql = "SELECT id ,`name`,`password`,pic,email FROM t_user WHERE id IN(SELECT user_id FROM t_user_project WHERE project_id = ?)";
		return db.executeQueryForList(sql, new UserRowMapper(),project_id);
	}
	
	public List<User> findAll() {
		String sql = "select id,`name`,`password`,pic,email from t_user";
		return db.executeQueryForList(sql, new UserRowMapper());
	}
	public boolean save(User user){
		String sql = "INSERT INTO t_user(id,`name`,`password`,pic,email) VALUES (?,?,?,?,?)";
		return db.executeSQL(sql, user.getId(),user.getName(),user.getPassword(),user.getPic(),user.getEmail());
		
	}
	
	public User findByUserId(String userid) {
		String sql = "SELECT id,`name`,`password`,email,pic FROM t_user WHERE id = ?";
		return db.executeQueryForObject(sql, new UserRowMapper(), userid);

	}
	
	
	public class UserRowMapper implements RowMapper<User>{

		public User mapRow(ResultSet rs) throws SQLException {
			User user = new User();
			user.setId(rs.getString("id"));
			user.setName(rs.getString("name"));
			user.setPassword(rs.getString("password"));
			user.setPic(rs.getString("pic"));
			user.setEmail(rs.getString("email"));
			return user;
		}
		
		
	}

	
	
}
